package com.kkd.config;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;

/**
 * @author 14587
 * @date 2021/1/14 23:08
 */
//自定义userRealm的时候，需要extends AuthorizingRealm
public class UserRealm extends AuthorizingRealm {

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("执行了授权");
        Subject subject = SecurityUtils.getSubject();
        Object principal = subject.getPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission((String) principal);
        return info;
    }

    //认证
    @Override//我们一般在这里进行认证
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("执行了认证");
        UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;
        //这里用户名和密码都要从数据库中取
        String username="admin";
        String password="123456";

        if (!userToken.getUsername().equals(username))return null;//这里会直接抛出异常

        //密码验证，要用shiro做

        return new SimpleAuthenticationInfo("user:update",password,"");
    }
}
